using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;
using NetWing.Common.Entity;

namespace NetWing.BPM.Admin.Nw_customform_user_MakeRoom.ashx
{
    /// <summary>
    /// 预约表 的摘要说明
    /// </summary>
    public class Nw_customform_user_MakeRoomHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<Nw_customform_user_MakeRoomModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<Nw_customform_user_MakeRoomModel>>(json);
                rpm.CurrentContext = context;
            }
            string err = "";
            switch (rpm.Action)
            {

                case "tuiyyj":
                    string tuiedNumber = common.mjcommon.getedNumber("TY");
                    int tuifmainInsertedId = 0;//财务主表ID
                    Nw_customform_user_MakeRoomModel t = new Nw_customform_user_MakeRoomModel();
                    t.InjectFrom(rpm.Entity);
                    t.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                    t.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                    t.tuiedNumber = tuiedNumber;
                    t.KeyId= rpm.KeyId;
                    t.up_time = DateTime.Now;
                    #region 数据库事务
                    SqlTransaction trantui = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {
                        //得到当前预约信息
                        DataRow ndr = SqlEasy.ExecuteDataRow("SELECT * from nw_customform_user_MakeRoom  where KeyId=" + t.KeyId + "");
                        //利用反射给model赋值
                        Nw_customform_user_MakeRoomModel roomOrdertemp = Entity.GetModelByDataRow<Nw_customform_user_MakeRoomModel>(ndr);

                        string[] upfields = {"up_time", "tuiednumber" };//注意字母要小写
                        DbUtils.tranUpdateOnlyUpdateFields(t, trantui, upfields);//只更新某字段的做法
                        MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
                        fmainModel.account = t.account;//账号  这个是从浏览器传过来的
                        fmainModel.accountid = t.accountid;//账号ID
                        fmainModel.add_time = DateTime.Now;
                        fmainModel.contact = SysVisitor.Instance.cookiesUserName;
                        fmainModel.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);
                        //fmainModel.dep = dep;//部门
                        fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        fmainModel.edNumber = tuiedNumber;
                        fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        fmainModel.unit = roomOrdertemp.maa_name;//用户
                        fmainModel.unitid = 0;//用户没注册所以是0
                        fmainModel.note = roomOrdertemp.maa_name + "退预约定金,预约ID是:" + roomOrdertemp.KeyId;
                        fmainModel.payment = -roomOrdertemp.maa_price;
                        fmainModel.total = -roomOrdertemp.maa_price;
                        fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
                        fmainModel.operate = SysVisitor.Instance.cookiesUserName;
                        tuifmainInsertedId = DbUtils.tranInsert(fmainModel, trantui);//往财务主表插入一条
                        //写财务明细表
                        MJFinanceDetailModel fdetailModel = new MJFinanceDetailModel();//初始化明细表模型
                        fdetailModel.financeId = tuifmainInsertedId;//财务主表ID
                        fdetailModel.ftype = "";
                        fdetailModel.edNumber = tuiedNumber;
                        fdetailModel.subject = "退预约定金";
                        fdetailModel.subjectid = 19;//19是退预约定金
                        fdetailModel.sumMoney = fmainModel.total;
                        fdetailModel.num = 1;
                        fdetailModel.sprice = fmainModel.total;
                        fdetailModel.username = roomOrdertemp.maa_name;
                        fdetailModel.mobile = roomOrdertemp.maa_tel;
                        fdetailModel.dep = "";
                        fdetailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                        fdetailModel.note = fmainModel.note;
                        fdetailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                        fdetailModel.add_time = DateTime.Now;
                        fdetailModel.up_time = DateTime.Now;
                        DbUtils.tranInsert(fdetailModel, trantui);//执行写入财务明细表
                        trantui.Commit();
                        context.Response.Write("{\"status\":1,\"msg\":\"退预约金成功！\"}");
                    }
                    catch (Exception e)
                    {
                        //tran.Rollback();//错误！事务回滚！
                        trantui.Dispose();//释放事务
                        LogModel log = new LogModel();
                        log.BusinessName = "退预约定金失败";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = e.Message;
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);
                        context.Response.Write("{\"status\":0,\"msg\":\"" + err + e.Message + "\"}");
                        //throw;
                    }

                    #endregion

                    break;

                case "add":
                    string edNumber = common.mjcommon.getedNumber("YY");
                    int fmainInsertedId = 0;//财务主表ID
                    Nw_customform_user_MakeRoomModel a = new Nw_customform_user_MakeRoomModel();
                    a.InjectFrom(rpm.Entity);
                    a.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                    a.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                    a.edNumber = edNumber;
                    if (a.maa_price>0)
                    {
                        a.maa_paystate = a.account + ",已支付";
                    }
                    else
                    {
                        a.maa_paystate = "未付";
                    }
                    a.add_time = DateTime.Now;
                    //context.Response.Write(Nw_customform_user_MakeRoomBll.Instance.Add(a));
                    #region 数据库事务
                    SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {
                        
                        int yyInsertID = DbUtils.tranInsert(a, tran);//往预约主表插入一条
                        //在房间表里更新预订信息

                        string roomsql = "update MJRooms set isding='是',isdingnote='"+a.maa_name+"预订"+a.maa_fx+"房号:"+a.maa_fh+"电话:"+a.maa_tel+ "'  where roomnumber='"+a.maa_fh+"' and depid="+SysVisitor.Instance.cookiesUserDepId+"";

                        DbUtils.tranUpdate(roomsql, tran);


                        MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
                        fmainModel.account = a.account;//账号
                        fmainModel.accountid = a.accountid;//账号ID
                        fmainModel.accountidb = a.accountid;
                        fmainModel.accountb = a.account;
                        fmainModel.add_time = DateTime.Now;
                        fmainModel.contact = SysVisitor.Instance.cookiesUserName;
                        fmainModel.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);
                        //fmainModel.dep = dep;//部门
                        fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        fmainModel.edNumber = a.edNumber;
                        fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        fmainModel.unit = a.maa_name;//用户
                        fmainModel.unitid = 0;//用户没注册所以是0
                        fmainModel.note = a.maa_name+"预约登记,预约ID是:"+yyInsertID;
                        fmainModel.payment =a.maa_price;
                        fmainModel.shifub = a.maa_price;//收款时默认第一个实付账号
                        fmainModel.total = a.maa_price;
                        fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
                        fmainModel.operate = SysVisitor.Instance.cookiesUserName;
                        fmainInsertedId = DbUtils.tranInsert(fmainModel, tran);//往财务主表插入一条
                        //写财务明细表
                        MJFinanceDetailModel fdetailModel = new MJFinanceDetailModel();//初始化明细表模型
                        fdetailModel.financeId = fmainInsertedId;//财务主表ID
                        fdetailModel.ftype = "";
                        fdetailModel.edNumber = edNumber;
                        fdetailModel.subject = "预约定金";
                        fdetailModel.subjectid = 4;//4是预约定金
                        fdetailModel.sumMoney = fmainModel.total;
                        fdetailModel.num = 1;
                        fdetailModel.sprice = fmainModel.total;
                        fdetailModel.username = a.maa_name;
                        fdetailModel.mobile = a.maa_tel;
                        fdetailModel.dep = "";
                        fdetailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                        fdetailModel.note = fmainModel.note;
                        fdetailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                        fdetailModel.add_time = DateTime.Now;
                        fdetailModel.up_time = DateTime.Now;
                        DbUtils.tranInsert(fdetailModel, tran);//执行写入财务明细表
                        tran.Commit();//提交数据库事务
                        context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");

                    }
                    catch (Exception e)
                    {
                        //tran.Rollback();//错误！事务回滚！
                        tran.Dispose();//释放事务
                        LogModel log = new LogModel();
                        log.BusinessName = "预约登记失败";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = e.Message;
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);
                        context.Response.Write("{\"status\":0,\"msg\":\"" + err + e.Message + "\"}");
                        //throw;
                    }


                    #endregion

                    break;
                case "edit":
                    Nw_customform_user_MakeRoomModel d = new Nw_customform_user_MakeRoomModel();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;

                    string[] upfieldsa = { "maa_md", "maa_fx", "maa_fh", "maa_name", "maa_sex", "maa_tel", "maa_num", "maa_yykfsj", "maa_yyrzsj", "maa_yytfsj", "note" };//注意字母要小写
                    //只更新某字段的做法
                    context.Response.Write(DbUtils.UpdateOnlyUpdateFields(d, upfieldsa));
                    break;
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(Nw_customform_user_MakeRoomModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                case "delete":
                    context.Response.Write(Nw_customform_user_MakeRoomBll.Instance.Delete(rpm.KeyId));
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.Nw_customform_user_MakeRoomDal.Instance.Delete(rpm.KeyIds));
                    break;
                default:
                    string sqlwhere = "(depid in (" + SysVisitor.Instance.cookiesDepartments + "))";
                    if (SysVisitor.Instance.cookiesIsAdmin == "True")
                    { //判断是否是超管如果是超管理，所有显示
                        sqlwhere = " 1=1 ";//如果是超管则不显示
                    }
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string str = " and " + FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere + str;
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    //默认排序keyid
                    string mysort = null;
                    if (rpm.Sort == null)
                    {
                        mysort = "keyid desc";
                    }
                    else
                    {
                        mysort = rpm.Sort;
                    }

                    var pcp = new ProcCustomPage(TableConvention.Resolve(typeof(Nw_customform_user_MakeRoomModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        OrderFields = mysort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt));
                    //旧的方法
                    //context.Response.Write(MJUserBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    //context.Response.Write(Nw_customform_user_MakeRoomBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(Nw_customform_user_MakeRoomModel));//数据库中的表名
                                                                                                                 //自定义的datatable和数据库的字段进行对应  
                                                                                                                 //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                                                 //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}